#!/usr/bin/env python
#
# Copyright 2012 Ville Rantanen
#
# this program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import sys,os
import subprocess
from argparse import ArgumentParser 
import Qalbum

# (c) ville.rantanen@helsinki.fi

DESCFILE='descriptions.csv'

def createdesc(path,list,options):
    ''' Runs imagemagick identify to create descriptions of images '''
    if len(list)==0:
        return
    if os.path.exists(os.path.join(path,DESCFILE)):
        if options.force:
            os.remove(os.path.join(path,DESCFILE))
        else:
            print('Descriptions exist, not overwriting.')
            return
    outfile=open(os.path.join(path,DESCFILE),'w')
    n=1
    nsum=len(list)
    for i in list:
        inpath=os.path.join(path,i)
        desc=create_description(inpath,options.format).rstrip().replace('\n','<br/>')
        outfile.write(i+"\t"+desc+'\n')
        outfile.flush()
        print('('+str(n)+'/'+str(nsum)+') '+i+"\t"+desc)
        n+=1
    return

def create_description(infile,format):
    if format=='AbsolutelyEverything':
        idargs=['identify','-verbose',infile+'[0]']
    else:
        idargs=['identify','-format',format,infile+'[0]']
    idp=subprocess.Popen(idargs,stdout=subprocess.PIPE)
    output = idp.stdout.read()
    return output

def traverse(path,options):
    ''' The recursive main function to create the thumbs and seek sub folders '''
    print(path)
    pathlist=Qalbum.getpathlist(path,options)
    imagelist=Qalbum.getimagelist(path,options)
    print(str(len(pathlist))+' paths')
    print(str(len(imagelist))+' images')
    createdesc(path,imagelist,options)
    if options.recursive:
        for p in pathlist:
            traverse(os.path.join(path,p),options)
    return

def execute():
    ''' Main execution '''
    parser=ArgumentParser()
    parser.add_argument("-v",action='version', version=Qalbum.__version__)
    parser.add_argument("-f",action="store_true",dest="force",default=False,
                      help="Force rewriting of descriptions")
    parser.add_argument("--format",type=str,dest="format",default="",
                      help="""Formatting string, see: http://www.imagemagick.org/script/escape.php. 
    Setting this option will override the presets""")
    parser.add_argument("-r",action="store_true",dest="recursive",default=False,
                      help="Recurse in to subfolders")
    parser.add_argument("-p",type=int,dest="preset",default=1,
                      help="presets for descriptions. \"-p 0\" to get the list")
    parser.add_argument("startpath",type=str,action="store",default=os.path.abspath('.'),nargs='?',
                      help="Start path for recursion")
    options=parser.parse_args()
    options.startpath=os.path.abspath(options.startpath)
    options=Qalbum.setupdefaultoptions(options)

    presets=[
        '%f: %[EXIF:DateTimeOriginal]',
        '%f: %wx%h %[size]',
        '%f<br/><i>%[EXIF:DateTimeOriginal] %[EXIF:ExposureTime]s F%[EXIF:FNumber]</i>',
        'AbsolutelyEverything']
    if options.preset<1:
        print "Presets:"
        for row in range(len(presets)):
            print row+1," ",presets[row]
        sys.exit(0)
    if options.format=="":
        if options.preset>len(presets):
            parser.error("No such preset, list with -p 0")
        options.format=presets[options.preset-1]
    
    traverse(options.startpath,options)
    return

execute()
sys.exit(0)
    

